from django.conf import settings
from django import forms
from django.utils.safestring import mark_safe

from accounts.models import RatePlan

# TODO: Possibly better regex: ([a-z0-9]*_?[a-z0-9]*)
alnum_regex = r'^\w+$'


class AccountLabelField(forms.RegexField):
	"""
	Form Field that ensures an Account label is alpha-numeric, proper lengths, and unique.
	Should only be used on forms that create a new Account.
	"""
	def __init__(self, *args, **kwargs):
		kwargs.update({
			'max_length': 25,
			'min_length': 3,
			'regex': alnum_regex,
			'error_messages': {'invalid': 'Please user letters, numbers and underscores only.'},
		})
		super(AccountLabelField, self).__init__(*args, **kwargs)

	def clean(self, label):
		label = super(AccountLabelField, self).clean(label)
		from accounts.models import Account
		if label in getattr(settings, 'RESERVED_SUBDOMAINS', []):
			raise forms.ValidationError("That subdomain is not available.  Please choose another.")
		try:
			account = Account.objects.get(label__iexact=label)
			raise forms.ValidationError("That subdomain is not available.  Please choose another.")
		except Account.DoesNotExist:
			return label


class UsernameField(forms.RegexField):
	"""
	Helper Field for making sure a username is a valid length / format.
	Prevents someone from using a username that's already in use by an auth.User superuser.
	"""
	def __init__(self, *args, **kwargs):
		kwargs.update({
			'max_length': 15,
			'min_length': 3,
			'regex': alnum_regex,
			'error_messages': {'invalid': 'Usernames must be letters, numbers and underscores only.'},
		})
		super(UsernameField, self).__init__(*args, **kwargs)

	def clean(self, username):
		username = super(UsernameField, self).clean(username)
		from django.contrib.auth.models import User
		try:
			user = User.objects.get(username__iexact=username)
			raise forms.ValidationError("That username is not available.  Please choose another.")
		except User.DoesNotExist:
			return username


class RatePlanField(forms.ModelChoiceField):
    
    def __init__(self, *args, **kwargs):
        kwargs.update({'empty_label':None})
        super(RatePlanField, self).__init__(RatePlan.objects.active(), *args, **kwargs)


# http://www.djangosnippets.org/snippets/937/
class ReadOnlyWidget(forms.Widget):
	def __init__(self, original_value, display_value):
		self.original_value = original_value
		self.display_value = display_value

		super(ReadOnlyWidget, self).__init__()

	def render(self, name, value, attrs=None):
		if self.display_value is not None:
			return mark_safe(unicode(self.display_value))
		return mark_safe(unicode(self.original_value))

	def value_from_datadict(self, data, files, name):
		return self.original_value

class ReadOnlyAdminFields(object):
	def get_form(self, request, obj=None):
		form = super(ReadOnlyAdminFields, self).get_form(request, obj)

		if hasattr(self, 'readonly'):
			for field_name in self.readonly:
				if field_name in form.base_fields:

					if hasattr(obj, 'get_%s_display' % field_name):
						display_value = getattr(obj, 'get_%s_display' % field_name)()
					else:
						display_value = None

					form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
					form.base_fields[field_name].required = False

		return form